package com.suning.generator.action;

import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.PsiType;
import com.suning.generator.util.ClipboardUtils;
import com.suning.generator.util.NotifyUtils;
import com.suning.generator.util.StringUtils;

/**
 * 生成JavaBean的单元测试
 *
 * @author bail
 * @date 2020/4/26
 */
public class GenerateJavaBeanAction extends BaseAction {

    private static final String JAVA_BEAN_FORMAT =
            "%s obj = new %s();\n" +
                    "%s" +
                    "obj.toString();";
    private static final String JAVA_BEAN_FIELD_FORMAT =
            "obj.set%s(%s);\n" +
                    "obj.get%s();\n";

    @Override
    public void doCommand(PsiClass psiClass, Project project) {
        String className = psiClass.getName();
        PsiField[] fields = psiClass.getFields();
        String fieldUpper;
        StringBuilder stringBuilder = new StringBuilder();
        for (PsiField f : fields) {
            // 排除serialVersionUID等static或final的字段
            if (!f.hasModifierProperty(PsiModifier.STATIC) && !f.hasModifierProperty(PsiModifier.FINAL)) {
                fieldUpper = StringUtils.toUpperFirstChar(f.getName());
                stringBuilder.append(String.format(JAVA_BEAN_FIELD_FORMAT, fieldUpper, getValue(f.getType()), fieldUpper));
            }
        }

        // 将单元测试内容设置到剪贴板
        ClipboardUtils.setClipboardString(String.format(JAVA_BEAN_FORMAT,
                className,
                className,
                stringBuilder.toString()
        ));
        NotifyUtils.notifyMessage(project);
    }

    private String getValue(PsiType psiType) {
        String typeName = psiType.getCanonicalText();
        if ("boolean".equals(typeName)) {
            return "true";
        } else if("byte".equals(typeName)) {
            return "(byte) 1";
        } else if("short".equals(typeName)) {
            return "(short) 1";
        } else if("char".equals(typeName)) {
            return "'1'";
        } else if("int".equals(typeName)) {
            return "1";
        } else if("float".equals(typeName)) {
            return "(float) 1.0";
        } else if("long".equals(typeName)) {
            return "1L";
        } else if("double".equals(typeName)) {
            return "1.0";
        }
        return "null";
    }

}
